package com.fjc.authorcation;

import com.fjc.domain.SysUser;
import com.fjc.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created by fjc on 2018/9/24.
 */
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CustomCredentialsMatcher customCredentialsMatcher;
//    @Bean
//    public CredentialsMatcher pwdMatcher(){
//        return new CustomCredentialsMatcher();
//    }

    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(customCredentialsMatcher);
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String)principalCollection.getPrimaryPrincipal();
        Set<Map> roles = sysUserService.findUserRoleByUsername(username);
        Set<Map> permissions = sysUserService.findRolePermissionByRole(roles);
        Set<String> rolestr = new HashSet<>();
        Set<String> permissionStr = new HashSet<>();
        for (Map map:roles) {
            rolestr.add(map.get("role").toString());
        }
        for (Map map:permissions) {
            permissionStr.add(map.get("permission").toString());
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(rolestr);
        info.addStringPermissions(permissionStr);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //自定义密码验证
        setCredentialsMatcher(customCredentialsMatcher);

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        SysUser user = sysUserService.findUserByUsername(usernamePasswordToken.getUsername());
        if(user == null){
//            throw new UnknownAccountException();
            return null;
        }else{
            AuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),this.getName());
            SecurityUtils.getSubject().getSession().setAttribute("userInfo",user);
            return info;
        }
    }
}
